package com.ccsoft.multithread.test;

import java.util.concurrent.locks.LockSupport;

/**
 * @author chanchaw
 * @create 2022-08-05 9:17
 * 线程编排，控制多个线程的执行顺序
 */
public class No2ThreadSchedule {

}

/**
 * 第一个方案：使用对象锁 synchronized 的 wait 方法
 * 控制两个线程的执行顺序
 */
class Prog1SynchronizedWait{
    static Object lock = new Object();
    static boolean isT2runned = false;

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            synchronized (lock){
                // 业务逻辑要放在 wait 之后 - 当线程被唤醒是继续执行 wait 之后的代码
                while(isT2runned == false){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("我是t1");
            }

        },"t1");

        Thread t2 = new Thread(()->{
            synchronized (lock){
                System.out.println("我是t2");
                isT2runned = true;
                lock.notifyAll();
            }

        },"t2");

        t1.start();
        t2.start();
    }
}

/**
 * 使用 LockSupport.park(); 控制两个线程的执行顺序
 */
class Prog2LockSupportPark {
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            LockSupport.park();
            System.out.println("我是t1");
        },"t1");

        Thread t2 = new Thread(()->{
            System.out.println("我是t2");
            LockSupport.unpark(t1);
        },"t2");


        t1.start();
        t2.start();
    }
}

